#include<SoftwareSerial.h>
#include <Servo.h>
const int trig = 3;
const int echo = 4; 
double distance;
int flag = 0;
Servo myservo;  // 定义Servo对象来控制
int pos = 0;
SoftwareSerial BT(8, 9); 
int min = 0;
void setup()
{
  Serial.begin(9600);
  BT.begin(9600);
  Serial.println("BT already!");
  myservo.attach(10);
}
void loop()
{
   digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  distance = pulseIn(echo, HIGH) / 58.0; 
  if(BT.read()=='1')
   {
    flag=1;
    myservo.write(90);
    }
   else if(BT.read()=='-1')
    {
      flag=-1;
      BT.println("将取消您车位的共享");
      }
  if(flag == 1)
   BT.println("您的车库目前处于使用状态");
     if(distance >13&&distance<50)
      {
      BT.print("共享结束，您本次的收益为");
      BT.print(min/60*50);
      BT.print("元");
      flag=-1;
      myservo.write(0);
      }
   else if(distance <= 20&&flag==0)//检测到车离开
   {
    BT.println("目前有车靠近您的车库");
    }
  
    else
    {
      min++;
      }
   
  delay(1000);

  Serial.println(distance);
}

 

